﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Leadtools.Codecs;
using Leadtools;
using Leadtools.WinForms;
using FastReport;

using MINERP.BLL.QC;
using MINERP.BLL.Common;
using MINERP.ComControls;
using System.IO;
using System.Drawing.Printing;

namespace MINERP.QC
{
    public partial class FrmCheckOrderInfo : FrmParent
    {
        //参数
        QCBLL _bll = new QCBLL();
        //属性
        private static FrmCheckOrderInfo _instance = null;
        public int userid;
        public int techid;
        private string picPath = "";
        List<MINERP.BLL.QC.QCBLL.CheckPhoto> photoList = new List<QCBLL.CheckPhoto>();
        public static FrmCheckOrderInfo GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmCheckOrderInfo();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }

        public FrmCheckOrderInfo()
        {
            InitializeComponent();
            base.InitiAuthority();
        }

        private void FrmCheckOrderInfo_Load(object sender, EventArgs e)
        {
            this.userid = base.userId;
            //txtOrderProductCode.Text = productCode;
            //btnOk.PerformClick();
            bool viewStyle = Properties.Settings.Default.ViewStyle;
            if (viewStyle)
            {
                splitContainerViewOrList.Panel1Collapsed = true;
                splitContainerViewOrList.Panel2Collapsed = false;
            }
            else
            {
                splitContainerViewOrList.Panel1Collapsed = false;
                splitContainerViewOrList.Panel2Collapsed = true;
            }

            ////printDocument1.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
            ////设置页边距
            //printDocument1.PrinterSettings.DefaultPageSettings.Margins.Left = 0;
            //printDocument1.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
            //printDocument1.PrinterSettings.DefaultPageSettings.Margins.Right = 0;
            //printDocument1.PrinterSettings.DefaultPageSettings.Margins.Bottom = 0;
            
            ////设置尺寸大小，如不设置默认是A4纸
            ////A4纸的尺寸是210mm×297mm，
            ////当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842
            ////当你设定的分辨率是150像素/英寸时，A4纸的尺寸的图像的像素是1240×1754
            ////当你设定的分辨率是300像素/英寸时，A4纸的尺寸的图像的像素是2479×3508，
            //printDocument1.DefaultPageSettings.PaperSize = new PaperSize("A4", 595, 842);
        }

        public void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                string productCode = FormatProductCode();
                SetOrderInfo(productCode);
                if (checkBoxAutoPrint.Checked)
                {
                    btnPrint_Click(sender, e);
                }
                txtOrderProductCode.SelectAll();
                txtOrderProductCode.Focus();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void Complete(string productCode)
        {
            if (_bll.IsNeedSetCompleted(productCode, techid))
            {
                _bll.UpdateWorkFlowList(productCode, userid, techid);
            }
        }
        //确认完成
        private void btnComplete_Click(object sender, EventArgs e)
        {
            try
            {
                string productCode = FormatProductCode();
                Complete(productCode);
                MessageBox.Show("质检完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void browser_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                string picPath = browser.SelectedItems[0].Tag.ToString();
                SetBigImage(picPath);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //按客户名模糊查询
        private void btnFind_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    Cursor = Cursors.WaitCursor;
            //    FrmFindByCtmName find = new FrmFindByCtmName();
            //    find.Frm = this;
            //    find.ShowDialog();
            //    Cursor = Cursors.Default;
            //}
            //catch (Exception ex)
            //{
            //    Cursor = Cursors.Default;
            //    MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
        }

        //--------------------------------公共方法-----------------------------------------------
        private void SetOrderInfo(string productCode)
        {
            try
            {
                //string code = txtOrderProductCode.Text.Trim();
                // if (code.Length < 10)
                // {
                //     int c = 0;
                //     try
                //     {
                //         c = Convert.ToInt32(code);
                //     }
                //     catch
                //     {
                //         MessageBox.Show("请输入正确的产品编号！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //         txtOrderProductCode.SelectAll();
                //         txtOrderProductCode.Focus();
                //         return;
                //     }
                //     code = "2" + string.Format("{0:d9}", c);
                // }
                photoList = new List<QCBLL.CheckPhoto>();
                List<MINERP.BLL.QC.QCBLL.CheckPhoto> photos = _bll.GetPhotosByOrderProductCode(productCode);
                if (photos == null || photos.Count == 0)
                {
                    MessageBox.Show("无照片产品！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //return;
                }

                lblOrderProductName.Text = photos[0].OrderProductName;
                lblCtmName.Text = photos[0].CtmName;
                lblShopName.Text = photos[0].ShopName;
                lblPhotoNum.Text = photos.Sum(p => p.ProductNum * p.PhotoNum).ToString();
                labelProductNum.Text = photos[0].ProductNum.ToString();
                photoList = photos;
                AddThumbs(photos);

            }
            catch
            {
                MessageBox.Show("照片不存在！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void AddThumbs(List<QCBLL.CheckPhoto> photos)
        {
            bool viewStyle = Properties.Settings.Default.ViewStyle;
            if (viewStyle)
            {
                splitContainerViewOrList.Panel1Collapsed = true;
                splitContainerViewOrList.Panel2Collapsed = false;
                browser.SelectedIndexChanged -= browser_SelectedIndexChanged;
                try
                {
                    browser.Items.Clear();
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    CodecsThumbnailOptions option = new CodecsThumbnailOptions();
                    option.LoadStamp = true;
                    option.MaintainAspectRatio = true;
                    option.Resample = true;
                    //option.ForceSize = true;
                    //option.bi
                    RasterImage img;
                    foreach (QCBLL.CheckPhoto p in photos)
                    {
                        try
                        {
                            img = codecs.ReadThumbnail(p.PicPath, option, 1);
                        }
                        catch //没有缩略图就读取原图                    {
                        {
                            img = codecs.Load(p.PicPath);
                        }

                        RasterImageListItem item = new RasterImageListItem(img, 1, p.PhotoRemark);
                        item.Tag = p.PicPath;
                        browser.Items.Add(item);
                    }
                    RasterCodecs.Shutdown();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                browser.SelectedIndexChanged += browser_SelectedIndexChanged;
            }
            else
            {
                splitContainerViewOrList.Panel1Collapsed = false;
                splitContainerViewOrList.Panel2Collapsed = true;

                gridControlphotos.DataSource = photos;
                gridControlphotos.RefreshDataSource();
            }
        }

        private void SetBigImage(string picPath)
        {
            try
            {
                lblPhotoName.Text = picPath.Substring(picPath.LastIndexOf("\\") + 1);
                RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();
                RasterImage img = codecs.Load(picPath);
                rasterImg.SizeMode = RasterPaintSizeMode.FitAlways;
                rasterImg.Image = img;
                RasterCodecs.Shutdown();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void FrmCheckOrderInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            //    if (e.CloseReason == CloseReason.UserClosing)
            //    {
            //        e.Cancel = true;
            //        this.Hide();
            //    }
            //this.Owner = null;
        }

        private void btnShowSelect_Click(object sender, EventArgs e)
        {

        }
        //打印条码
        private void btnPrint_Click(object sender, EventArgs e)
        {
            btnPrint1.Enabled = false;

            if (txtOrderProductCode.Text.Trim() != string.Empty)
            {
                string productCode = FormatProductCode();
                Complete(productCode);
                if (_bll.IsProductExist(productCode))
                {
                    DataTable dt = _bll.GetPrintInfo(productCode);
                    dt.WriteXml(@"C:\windows\xmlData\PrintQCReport.xml", XmlWriteMode.WriteSchema);
                    Report fasrReport = new Report();
                    try
                    {
                        fasrReport.Load(Application.StartupPath + "\\frQC.frx");
                        //fasrReport.RegisterData(dt, "Table");
                    }
                    catch (Exception)
                    {

                        MessageBox.Show("加载报表失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnPrint1.Enabled = true;
                        return;

                    }
                    try
                    {
                        fasrReport.PrintSettings.ShowDialog = chkShowPrintdialog.Checked;
                        fasrReport.Print();
                    }
                    catch { }

                    //修改outprocessRecord表的EndProductTime\status2

                    try
                    {

                        _bll.CompletedFactoryWork(productCode);

                    }
                    catch (Exception)
                    {

                        MessageBox.Show("结束异常，确定继续!");
                        btnPrint1.Enabled = true;
                    }

                }
                else
                {
                    MessageBox.Show("没有找到该产品的信息！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请输入产品号！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            btnPrint1.Enabled = true;
            txtOrderProductCode.SelectAll();
            txtOrderProductCode.Focus();
        }

        private string FormatProductCode()
        {

            string code = txtOrderProductCode.Text.Trim();
            if (string.IsNullOrEmpty(code))
            {
                MessageBox.Show("请输入产品号！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            if (code.Length < 10)
            {
                int c = Convert.ToInt32(code);
                code = "2" + string.Format("{0:d9}", c);
            }
            return code;
        }

        private void FrmCheckOrderInfo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 43)
            {
                btnPrint1.PerformClick();
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            FrmSelect frmSelect = new FrmSelect();
            frmSelect.SelectProduct += new SelectProductEventHander(SelectProduct);
            frmSelect._techid = CurrentTechID;
            frmSelect.ShowDialog();
        }

        private void SelectProduct(string productCode)
        {
            txtOrderProductCode.Text = productCode;
            btnOk.PerformClick();
        }

        private void btnChat_Click(object sender, EventArgs e)
        {
            frmMain.GetInstance(this.userid);

        }

        private void txtOrderProductCode_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void btnReCheck_Click(object sender, EventArgs e)
        {
            MINERP.ComControls.Froms.FrmReCheck frm = new MINERP.ComControls.Froms.FrmReCheck();
            frm.ShowDialog();
        }

        private void checkBoxPhotoView_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxPhotoView.Checked == true)
            {
                Properties.Settings.Default.ViewStyle = true;
                Properties.Settings.Default.Save();
            }
            else
            {
                Properties.Settings.Default.ViewStyle = false;
                Properties.Settings.Default.Save();
            }
        }

        private void gridViewPhotos_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                this.Cursor = Cursors.WaitCursor;
                MINERP.BLL.QC.QCBLL.CheckPhoto photo = (MINERP.BLL.QC.QCBLL.CheckPhoto)gridViewPhotos.GetRow(e.RowHandle);
                picPath = photo.PicPath;
                SetBigImage(photo.PicPath);
                this.Cursor = Cursors.Default;
            }
        }

        private void gridViewPhotos_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;

            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString().Trim();

            }
        }

        private void buttonPrintersmall_Click(object sender, EventArgs e)
        {
            //byte[] input = new Byte[90000];
            //if(string.IsNullOrEmpty(picPath))
            //{
            //    if(photoList.Count==0)
            //    {
            //        picPath="";

            //    }else
            //    {
            //        picPath=photoList.OrderBy(o=>o.PhotoName).FirstOrDefault().PicPath;
            //    }

            //}
            if (photoList.Count == 0)
            {
                MessageBox.Show("未选中产品", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                return;
            }
            //FileStream fs = new FileStream(picPath,FileMode.Open,FileAccess.Read);
            //fs.Read(input,0,90000);
            printDocument1.DefaultPageSettings.Landscape = true;

            printDocument1.Print();


        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int thumbWidth = 200;
            //Image IM = Image.FromFile(picPath);
            //Image pThumbnail = IM.GetThumbnailImage(100, 100,null,IntPtr.Zero);
            //e.Graphics.DrawImage(pThumbnail, 20, 20);
            int CurrX =0, CurrY = 5;
            int CurrStrX, CurrStry = 0;
            MINERP.BLL.QC.QCBLL.CheckPhoto firstPhoto=photoList.FirstOrDefault();
            e.Graphics.DrawString(firstPhoto.ShopName + "\\" + firstPhoto.CtmName + "\\" + firstPhoto.OrderProductName + "\\" + firstPhoto.OrderProductCode + "\\" + photoList.Count()+"页", new Font("Arial", 10), Brushes.Black, CurrX, CurrY, new StringFormat());
            CurrY +=20;
            foreach (MINERP.BLL.QC.QCBLL.CheckPhoto photo in photoList)
            {
                Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                using (Bitmap img = new Bitmap(photo.PicPath))
                {

                    int thumbHeight = thumbWidth * img.Height / img.Width;
                    Image myThumbnail = img.GetThumbnailImage(thumbWidth, thumbHeight, myCallback, IntPtr.Zero);

                    Rectangle destRect = new Rectangle(CurrX, CurrY, thumbWidth, thumbHeight);
                    e.Graphics.DrawImage(myThumbnail, destRect, 0, 0, thumbWidth, thumbHeight, System.Drawing.GraphicsUnit.Pixel);
                  

                    CurrStrX = CurrX + thumbWidth / 2-45;
                    CurrStry = CurrY + thumbHeight + 5;
                    e.Graphics.DrawString(photo.PhotoBarCode+"\\"+photo.PhotoName, new Font("Arial", 10), Brushes.Black, CurrStrX, CurrStry, new StringFormat());

                    e.Graphics.DrawLine(new Pen(Color.Black), CurrX, CurrY, CurrX + thumbWidth, CurrY); //上
                    e.Graphics.DrawLine(new Pen(Color.Black), CurrX, CurrStry, CurrX + thumbWidth, CurrStry); //下
                    e.Graphics.DrawLine(new Pen(Color.Black), CurrX, CurrY, CurrX, CurrStry); //左
                    e.Graphics.DrawLine(new Pen(Color.Black), CurrX + thumbWidth, CurrY, CurrX + thumbWidth, CurrStry); //右
                    CurrX = CurrX + thumbWidth + 15;
                    if (CurrX >= 908)
                    {
                        CurrY = CurrY + thumbHeight +25;
                        CurrX = 0;
                    }
                    if (CurrY > e.PageBounds.Height)
                    {
                        e.HasMorePages = true;
                        return;

                    }
                }

            }
            e.HasMorePages = false;
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        private void groupControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void buttonPrintPhotoINFO_Click(object sender, EventArgs e)
        {
            FrmPrintPhotoInfo frm = new FrmPrintPhotoInfo();
            frm.Show();
        }


    }
}
